<?php
// +----------------------------------------------------------------------
// | Copyright (c) 2015 http://www.itaoke.org All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author:  Caption <Caption@163.com> QQ 1674653
// +----------------------------------------------------------------------

namespace Wap\Controller;
use Common\Controller\FirstendController;

class IndexController extends FirstendController {
	
	public function _initialize() {
		parent::_initialize();
		$this->_mod = D('Items');
		$this->_brandmod = D('Brand');
		$this->_cate_mod = D('ItemsCate');
		$this->page_size=C('itk_wap_pernum');
		C('DATA_CACHE_TIME',C('itk_site_cachetime'));
	}

	/**
	 ** 首页（全部）
	 **/
	public function index() {
		$p		= I('p',1 ,'intval'); //页码
		$sort	= I('sort', 'default', 'trim'); //排序
		$cid	= I('cid',0,'intval');
		$k		= I('k','');
		$price	= I('price',0,'intval');
//		$id=I('id',0,'intval');
		$data=array(
				'status'=>0,
				'list'=>''
		);
		
		$order = 'ordid asc';
		switch ($sort){
			case 'new':
				$order.= ', coupon_start_time DESC';
				break;
			case 'price':
				$order.= ', coupon_price ASC';
				break;
			case 'rate':
				$order.= ', coupon_rate ASC';
				break;
			case 'hot':
				$order.= ', volume DESC';
				break;
			case 'after':
				$order.= ', quan DESC';
				break;
			case 'default':
				if('magic' == C('itk_index_sort')){
					$order.= ', astime DESC, pic_url asc';
				}else{
					$order.= ', '.C('itk_index_sort');
				}
				break;
		}

		if(C('itk_index_not_text')){
			$not_arr = explode(",",C('itk_index_not_text'));
			$arrs =array();
			foreach($not_arr as $key =>$value){
				$arrs[] = '%'.$value.'%';
			}
			$where['title'] =array('notlike',$arrs,'AND');
		}
		if ($cid !=0) {
			$id_arr = $this->_cate_mod->get_child_ids($cid, true);
			$where['cate_id'] = array('IN', $id_arr);
			
			$this->assign('cname',$this->_cate_mod->getFieldById($cid,'name'));
		}
		
		$where['coupon_end_time'] = array('egt',time());
		if(C('itk_index_shop_type')){$where['shop_type'] = C('itk_index_shop_type');}
		if(C('itk_index_mix_price')>0){$where['coupon_price'] = array('egt',C('itk_index_mix_price'));}
		if(C('itk_index_max_price')>0){$where['coupon_price'] = array('elt',C('itk_index_max_price'));}
		if(C('itk_index_mix_price')>0 && C('itk_index_max_price')>0){$where['coupon_price'] = array(array('egt',C('itk_index_mix_price')),array('elt',C('itk_index_max_price')),'and');}
		if(C('itk_index_mix_volume')>0){$where['volume'] = array('egt',C('itk_index_mix_volume'));}
		if(C('itk_index_max_volume')>0){$where['volume'] = array('elt',C('itk_index_max_volume'));}
		if(C('itk_index_mix_volume')>0 && C('itk_index_max_volume')>0){$where['volume'] = array(array('egt',C('itk_index_mix_volume')),array('elt',C('itk_index_max_volume')),'and');}
		$where['pass'] = '1';
		$where['isshow'] = '1';

		if($price!=0){
			$where['coupon_price'] = array('ELT', $price);
		}
		if($k){
			$where['title'] = array('like', '%' . $k . '%');
		}
		$where['isq']=1;
		$where['status']='underway';
		
		// 滚动刷新
		if(IS_AJAX){
			$count = $this->_mod->where($where)->count();
			$pager = $this->_pager($count, $this->page_size);
			$data['page']=$pager->wxshow();
			
			$start = $this->page_size * ($p - 1) ;
			$items = $this->_mod->where($where)->order($order)->limit($start . ',' . $this->page_size)->select();
			for($i=0;$i<count($items);$i++){
				$items[$i]['url']= U('Item/index',array('id'=>$items[$i]['id'] /*,'p'=>$p*/));
				$items[$i]['after_price']=$items[$i]['coupon_price']-$items[$i]['quan'];
			}
			$data['pages']=$pager->totalPages;
			$data['list']=$items;
			$this->ajaxReturn(0,'',$data);
		}
		
		$this->reckCount($where);
		$this->assign('p',$p);
		$this->assign('sort',$sort);
		$this->assign('pager','index');
		$this->assign('cid',$cid);
		$this->assign('k',$k);

		$this->assign('price',$price);
		$this->assign('nav_curr', 'index');
		
		if($sort=='hot')
			$this->assign('nav_curr', 'hot');
		if($cid!=0)
			$this->assign('nav_curr', 'cid');
		if($price==10)
			$this->assign('nav_curr', 'jiu');
		
		if($sort=='after' && $cid!=0)
			$this->assign('nav_curr', 'after');
		if($cid!=0 && $sort=='hot')
			$this->assign('nav_curr', 'chot');

		$this->assign('dummy',C('itk_wap_dummy'));
		$this->assign('dummy_times',C('itk_dummy_times')!='' ? C('itk_dummy_times'):30);
		$this->assign('foot_curr','index');
		$this->_config_seo(C('itk_seo_config.index'));
		$this->display();
	}


	
	/**
	 * 计算不同条件的个数,并显示分页
	 * @param unknown $where
	 * @param unknown $mod
	 */
	private function reckCount($where){
		$count = $this->_mod->where($where)->count();
		$pager = $this->_pager($count, $this->page_size);
		$this->assign('page', $pager->wxshow());

		if( (false === $totalPages = F('totalPages')) ||  F('totalPages') != $pager->totalPages){
			S('totalPages', $pager->totalPages);
			F('totalPages', $pager->totalPages);
		}
		$this->assign('tp',$pager->totalPages);
	}
	
	/**
	 ** 搜索
	 **/
	public function so() {
		$sort	= I('sort', 'new', 'trim'); //排序
		$cid	= I('cid','','intval');
		$k		= I('k','');
		$data=array(
			'status'=>0,
			'list'=>''
		);
		
		$k = urldecode($k);
		$order	= 'ordid asc ,id desc';
		switch ($sort) {
			case 'new':
				$order.= ', coupon_start_time DESC';
				break;
			case 'price':
				$order.= ', coupon_price ASC';
				break;
			case 'hot':
				$order.= ', volume DESC';
				break;
			case 'rate':
				$order.= ', coupon_rate ASC';
				break;
			case 'default':
				if('magic' == C('itk_index_sort')){
					$order.= ', astime DESC, pic_url asc';
				}else{
					$order.= ', '.C('itk_index_sort');
				}
		}

		if($k){
			$where['title'] = array('like', '%' . $k . '%');
			$this->assign('k',$k);
		}

		if ($cid) {
			$id_arr = $this->_cate_mod->get_child_ids($cid, true);
			$map['cate_id'] = array('IN', $id_arr);
			$this->assign('cid',$cid);
		}
		
		$where['coupon_rate'] = array('lt',10000);
		$where['pass'] = '1';
		$where['coupon_end_time'] = array('egt',time());
		
		$page_size = 36;
		$p = I('p',1, 'intval'); //页码

		$count = $this->_mod->where($where)->count();
		$pager = $this->_pager($count, $page_size);
		$data['page']=$pager->wxshow();
		
		$start = $page_size * ($p - 1) ;
		$items = $this->_mod->where($where)->order($order)->limit($start . ',' . $page_size)->select();
		for($i=0;$i<count($items);$i++){
			$items[$i]['url']= C('itk_wap_url').U('Item/index',array('id'=>$items[$i]['id'],'p'=>$p));
		}
		$data['list']=$items;
		$this->ajaxReturn(0,'',$data);

	}

	public function shortcut(){
		$Shortcut = "[InternetShortcut]
		URL=".C('itk_site_url')."
		IDList=
		[{000214A0-0000-0000-C000-000000000046}]
		Prop3=19,2
		";
		Header("Content-type: application/octet-stream");
		header("Content-Disposition: attachment; filename=".C('itk_site_name').".url;");
		echo $Shortcut;
	}

	/**
	 * 分类
	 */
	public function cate(){
		$cid	=	I('cid','', 'intval');
		$sort	=	I('sort', 'default', 'trim'); //排序
		$status =	I('status', 'all', 'trim'); //排序
		$sex	=	I('sex', 'all', 'trim');
		$order	=	'ordid asc ';
		 
		if(C('itk_site_cache')){
			$file = 'cinfo_'.$cid;
			if(false === $cinfo = S($file)){
				$cinfo = $this->_cate_mod->where(array('id'=>$cid))->find();
				S($file,$cinfo);
			}
		}else{
			$cinfo = $this->_cate_mod->where(array('id'=>$cid))->find();
		}
		!$cinfo && $this->_404();

		if($cinfo['pid']=='0'){
			$cinfo['pid'] = $cid;}else{
				$itb=explode("|",$cinfo['spid']);
				$cinfo['pid'] = $itb[0];
			}
			switch ($sort) {
				case 'new':
					$order.= ', coupon_start_time DESC';
					break;
				case 'price':
					$order.= ', price DESC';
					break;
				case 'hot':
					$order.= ', volume DESC';
					break;
				case 'rate':
					$order.= ', coupon_rate ASC';
					break;
				case 'default':
					$order.= ', '.$cinfo['sort'];
			}
			switch ($sex) {
				case 'man':
					$map['sex']= '1';
					break;
				case 'woman':
					$map['sex']= '2';
					break;
			}
			switch ($status) {
				case 'all':
					$map['status']="underway";
					break;
				case 'underway':
					$map['status']="underway";
					break;
				case 'sellout':
					$map['status']="sellout";
					break;
			}
			if($cinfo['shop_type']){$map['shop_type'] = $cinfo['shop_type'];}
			if($cinfo['mix_price']>0){$map['coupon_price'] = array('egt',$cinfo['mix_price']);}
			if($cinfo['max_price']>0){$map['coupon_price'] = array('elt',$cinfo['max_price']);}
			if($cinfo['max_price']>0 && $cinfo['mix_price']>0){$map['coupon_price'] = array(array('egt',$cinfo['mix_price']),array('elt',$cinfo['max_price']),'and');}
			if($cinfo['mix_volume']>0){$map['volume'] = array('egt',$cinfo['mix_volume']);}
			if($cinfo['max_volume']>0){$map['volume'] = array('elt',$cinfo['max_volume']);}
			if($cinfo['max_volume']>0 && $cinfo['mix_volume']>0){$map['volume'] = array(array('egt',$cinfo['mix_volume']),array('elt',$cinfo['max_volume']),'and');}
			if($cinfo['thiscid']==0){
				$id_arr = $this->_cate_mod->get_child_ids($cid, true);
				$map['cate_id'] = array('IN', $id_arr);
				$today_wh['cate_id'] = array('IN', $id_arr);
			}
			$today_str = mktime(0,0,0,date("m"),date("d"),date("Y"));
			$tomorr_str = mktime(0,0,0,date("m"),date("d")+1,date("Y"));
			$today_wh['coupon_start_time'] = array(array('egt',$today_str),array('elt',$tomorr_str)) ;
			$today_wh['pass'] = '1';
			$id_arr = $this->_cate_mod->get_child_ids($cid, true);
			$today_wh['cate_id'] = array('IN', $id_arr);
			$tomorr_wh['cate_id'] = array('IN', $id_arr);
			$today_wh['isshow'] = '1';
			$tomorr_wh['coupon_start_time'] = array(array('egt',$tomorr_str)) ;
			$tomorr_wh['pass'] = '1';
			$tomorr_wh['isshow'] = '1';


			if(C('itk_site_cache')){
				$md_id = md5(implode("-",$today_wh));
				$file = 'cate_today_item_'.$md_id;
				if(false === $today_item = S($file)){
					$today_item = $this->_mod->where($today_wh)->count();
					S($file,$today_item);
				}
			}else{
				$today_item = $this->_mod->where($today_wh)->count();
			}
			if(C('itk_site_cache')){
				$md_id = md5(implode("-",$tomorr_wh));
				$file = 'cate_today_item_'.$md_id;
				if(false === $tomorr_item = S($file)){
					$tomorr_item = $this->_mod->where($tomorr_wh)->count();
					S($file,$tomorr_item);
				}
			}else{
				$tomorr_item = $this->_mod->where($tomorr_wh)->count();
			}

			$this->assign('today_item', $today_item);
			$this->assign('tomorr_item', $tomorr_item);
			$this->assign('cid',$cid);
			$this->assign('pager','cate');
			$this->assign('cinfo',$cinfo);
			if($cinfo['wait_time'] == '1'){
				$map['coupon_start_time'] = array('egt',time());
			}elseif($cinfo['wait_time'] =='2'){
				$map['coupon_start_time'] = array('elt',time());
			}
			if($cinfo['end_time'] == '1'){
				$map['coupon_end_time'] = array('egt',time());
			}
			if($cinfo['ems'] == '1'){
				$map['ems'] = '1';
			}
			$map['coupon_rate'] = array('lt',10000);
			$map['pass']="1";
			$map['isshow'] = '1';
			$index_info['sort']=$sort;
			$index_info['sex']=$sex;
			$index_info['status']=$status;
			$index_info['cid']=$cid;
			$page_size = 36;
			$p = I('p',1,'intval'); //页码
			$index_info['p']=$p;
			$start = $page_size * ($p - 1) ;

			if (false === $cate_list = S('cate_list')) {
				$cate_list = D('ItemsCate')->cate_cache();
			}

			$this->assign('cate_list', $cate_list); //分类


			if(C('itk_site_cache')){
				$file = 'cate_subnav_'.$cid;
				if(false === $subnav = S($file)){
					$subnav = $this->_cate_mod->where(array('pid'=>$cid,'status'=>1))->order(ordid,desc)->select();
					if($cinfo['pid'] && !$subnav){
						$subnav = $this->_cate_mod->where(array('pid'=>$cinfo['pid'],'status'=>1))->order(ordid,desc)->select();
					}
					S($file,$subnav);
				}
			}else{
				$subnav = $this->_cate_mod->where(array('pid'=>$cid,'status'=>1))->order(ordid,desc)->select();
				if($cinfo['pid'] && !$subnav){
					$subnav = $this->_cate_mod->where(array('pid'=>$cinfo['pid'],'status'=>1))->order(ordid,desc)->select();
				}
			}
			$this->assign('subnav', $subnav);


			if(C('itk_site_cache')){
				$mdarray['cid'] = $cid;
				$mdarray['sort'] = $sort;
				$mdarray['sex'] = $sex;
				$mdarray['status'] = $status;
				$mdarray['p'] = $p;
				$mdarray['order'] = $order;
				$md_id = md5(implode("-",$mdarray));
				$file = 'cate_'.$md_id;
				if(false === $items = S($file)){

					$items_list = $this->_mod->where($map)->order($order)->limit($start . ',' . $page_size)->select();
					$items = array();
					$pagecount = 0;
					$seller_arr = array();
					$sellers = '';
					foreach($items_list as $key=>$val){
						$items['item_list'][$key]			= $val;
						$items['item_list'][$key]['class']	= $this->_mod->status($val['status'],$val['coupon_start_time'],$val['coupon_end_time']);
						$items['item_list'][$key]['zk']		= round(($val['coupon_price']/$val['price'])*10, 1);
						$items['item_list'][$key]['itemurl']	= C('itk_site_url').'/item/'.$val['id'].'.html';
						$items['item_list'][$key]['jumpurl']		= C('itk_site_url').'/jump/'.$val['id'].'.html';
						if(!$val['click_url']){
							$items['item_list'][$key]['click_url']	= C('itk_site_url').'/jump/'.$val['id'].'.html';
						}
						if($val['coupon_start_time']>time()){
							$items['item_list'][$key]['click_url']	= C('itk_site_url').'/item/'.$val['id'].'.html';
							$items['item_list'][$key]['timeleft'] = $val['coupon_start_time']-time();
						}else{
							$items['item_list'][$key]['timeleft'] = $val['coupon_end_time']-time();
						}
						$items['item_list'][$key]['cate_name']		=$cate_list['p'][$val['cate_id']]['name'];
						$url = C('itk_site_url').U('Item/index',array('id'=>$val['id']));
						$items['item_list'][$key]['url'] = urlencode($url);
						$items['item_list'][$key]['urltitle'] = urlencode($val['title']);
						$items['item_list'][$key]['price'] = number_format($val['price'],1);
						$items['item_list'][$key]['coupon_price'] = number_format($val['coupon_price'],1);
						$pagecount++;
						if($val['sellerId']){
							$items['seller_arr'][] = $val['sellerId'];
						}
					}


					S($file,$items);
				}
			}else{

				$items_list = $this->_mod->where($map)->order($order)->limit($start . ',' . $page_size)->select();
				$items = array();
				$pagecount = 0;
				$seller_arr = array();
				$sellers = '';
				foreach($items_list as $key=>$val){
					$items['item_list'][$key]			= $val;
					$items['item_list'][$key]['class']	= $this->_mod->status($val['status'],$val['coupon_start_time'],$val['coupon_end_time']);
					$items['item_list'][$key]['zk']		= round(($val['coupon_price']/$val['price'])*10, 1);
					$items['item_list'][$key]['itemurl']	= C('itk_site_url').'/item/'.$val['id'].'.html';
					$items['item_list'][$key]['jumpurl']		= C('itk_site_url').'/jump/'.$val['id'].'.html';
					if(!$val['click_url']){
						$items['item_list'][$key]['click_url']	=C('itk_site_url').'/jump/'.$val['id'].'.html';
					}
					if($val['coupon_start_time']>time()){
						$items['item_list'][$key]['click_url']	=C('itk_site_url').'/item/'.$val['id'].'.html';
						$items['item_list'][$key]['timeleft'] = $val['coupon_start_time']-time();
					}else{
						$items['item_list'][$key]['timeleft'] = $val['coupon_end_time']-time();
					}
					$items['item_list'][$key]['cate_name']		=$cate_list['p'][$val['cate_id']]['name'];
					$url = C('itk_site_url').U('Item/index',array('id'=>$val['id']));
					$items['item_list'][$key]['url'] = urlencode($url);
					$items['item_list'][$key]['urltitle'] = urlencode($val['title']);
					$items['item_list'][$key]['price'] = number_format($val['price'],1);
					$items['item_list'][$key]['coupon_price'] = number_format($val['coupon_price'],1);
					$pagecount++;
					if($val['sellerId']){
						$items['seller_arr'][] = $val['sellerId'];
					}

				}

			}
			if(isset($cid)){
				$catename = D('ItemsCate')->where(array('id'=>$cid))->getField('name');
				$pid = D('ItemsCate')->where(array('id'=>$cid))->getField('pid');
			}

			$this->assign('catename', $catename);
			$this->assign('pid', $pid);

			$seller_arr = array_unique($items['seller_arr']);
			$sellers = implode(",",$seller_arr);
			$this->assign('sellers', $sellers);
			if(IS_AJAX){
				if(!$items){$this->ajaxReturn(0, '加载完成');}
				$this->assign('items_list', $items['item_list']);
				$resp = $this->fetch('ajax');
				$this->ajaxReturn(1, '', $resp);
			}
			$this->assign('pagecount', $pagecount);


			$this->assign('items_list', $items['item_list']);
			$this->assign('index_info',$index_info);

			if(C('itk_site_cache')){
				$file = 'cate_count_'.$cid;
				if(false === $count = S($file)){
					$count = $this->_mod->where($map)->count();
					S($file,$count);
				}
			}else{
				$count = $this->_mod->where($map)->count();
			}

			$pager = $this->_pager($count, $page_size);
			$this->assign('page', $pager->jshow());
			$this->assign('total_item',$count);
			$this->assign('ajaxurl',U('Index/cate',array('cid'=>$cid,'p'=>$index_info['p'],'sort'=>$index_info['sort'])));
			$this->assign('ajaxurl',U('Index/cate',array('cid'=>$cid,'p'=>$index_info['p'],'sex'=>$index_info['sex'])));
			if($cinfo['pid']==1){
				$curr = 'fushi';
			}
			if($cinfo['pid']==2){
				$curr = 'muying';
			}
			if($cinfo['pid']==3){
				$curr = 'jujia';
			}
			if($cinfo['pid']==4){
				$curr = 'qita';
			}
			$this->assign('nav_curr', $curr);
			$this->_config_seo(C('itk_seo_config.cate') , array(
					'cate_name' => $cinfo['name'],
					'seo_title' => $cinfo['seo_title'],
					'seo_keywords' => $cinfo['seo_keys'],
					'seo_description' => $cinfo['seo_desc'],
			));
			$this->display();
	}

	/**
	 * 获取虚拟在线人数
	 */
	public function getdummy(){
		if(!IS_AJAX) return;
		$res=M('User')->where("isweixin=1")->order('rand()')->limit(1)->select();
		$res=$res[0];
		if($res==''){
			$_r['status']=-1;
		}else{
			$_r['status']=0;
		}
		
		$_r['one_user_info']=$res;
		$coupons=array(2,5,10,15,20,25,30,35,40,45,50,60,70,80,90,100);
		$i=rand(0,15);
		$_r['random_coupons']=$coupons[$i] ;
		$this->ajaxReturn(0,'',$_r);
	}
}
?>